import {
  getToken,
  setToken,
  removeToken,
  cook,
  removeCook
} from '@/utils/auth';
import {
  resetRouter
} from '@/router';

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    // avatar: '/images/avatar.gif',
    avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80',
    supplier_auth: cook('supplier_auth') || false, // 供应商状态的话 false表示未审核
    supplier_type: cook('supplier_type') || 1 // 账号类型，1内部账号，2供应商账号
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    // 重置状态
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    // 设置token
    state.token = token;
  },
  SET_NAME: (state, name) => {
    // 设置用户名
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    // 设置头像
    state.avatar = avatar;
  },

  SET_SUPPLIER_AUTH: (state, auth) => {
    // 设置 auth
    state.supplier_auth = auth;
  },
  SET_SUPPLIER_TYPE: (state, type) => {
    // 设置 type
    state.supplier_type = type;
  },
  SET_MERCHANTS_ID: (state, merchants) => {
    // 设置 商户ID
    state.merchants_id = merchants;
  }
};

const actions = {
  setToken({
    commit,
    state
  }, token) {
    // console.log(commit, state, token);
    setToken(token);
    commit('SET_TOKEN', token);
  },
  setSupplierAuth({
    commit,
    state
  }, auth) {
    // console.log(commit, state, auth);
    cook('supplier_auth', auth);
    commit('SET_SUPPLIER_AUTH', auth);
  },

  setSupplierType({
    commit,
    state
  }, type) {
    // console.log(commit, state, type);
    cook('supplier_type', type);
    commit('SET_SUPPLIER_TYPE', type);
  },

  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      console.log('logout');
      removeCook(['supplier_auth', 'supplier_type', 'token']);
      commit('RESET_STATE');
      resetRouter();
      location.reload();
      resolve();
    });
  },

  // 清除登录token，登录状态等，
  resetToken({
    commit
  }) {
    return new Promise((resolve) => {
      removeCook(['supplier_auth', 'supplier_type', 'token']);
      commit('RESET_STATE');
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
